#!/bin/bash
# 简化版服务器配置脚本 - 专注于 CentOS 8

set -e

echo "=================================="
echo "🚀 OY 项目服务器初始化（简化版）"
echo "=================================="

# 1. 备份并清理旧源
echo "备份旧配置..."
mkdir -p /etc/yum.repos.d/backup
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/ 2>/dev/null || true

# 2. 创建阿里云镜像源（CentOS 8）
echo "创建新的镜像源配置..."
cat > /etc/yum.repos.d/CentOS-Base.repo <<EOF
[BaseOS]
name=CentOS-8 - BaseOS - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos-vault/8.5.2111/BaseOS/x86_64/os/
gpgcheck=0
enabled=1

[AppStream]
name=CentOS-8 - AppStream - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos-vault/8.5.2111/AppStream/x86_64/os/
gpgcheck=0
enabled=1

[extras]
name=CentOS-8 - Extras - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos-vault/8.5.2111/extras/x86_64/os/
gpgcheck=0
enabled=1
EOF

echo "✅ 配置文件已创建"
cat /etc/yum.repos.d/CentOS-Base.repo

# 3. 清理缓存
echo ""
echo "清理缓存..."
yum clean all
rm -rf /var/cache/yum/* /var/cache/dnf/*

# 4. 测试源
echo ""
echo "测试镜像源..."
yum repolist

# 5. 安装 Nginx
echo ""
echo "安装 Nginx..."
yum install -y nginx

# 6. 安装 unzip
echo ""
echo "安装 unzip..."
yum install -y unzip

# 7. 创建项目目录
echo ""
echo "创建项目目录..."
mkdir -p /var/www/oy-promotion
chown -R nginx:nginx /var/www/oy-promotion
chmod -R 755 /var/www/oy-promotion

# 8. 配置防火墙
echo ""
echo "配置防火墙..."
if systemctl is-active --quiet firewalld; then
    firewall-cmd --permanent --add-service=http
    firewall-cmd --permanent --add-service=https
    firewall-cmd --reload
    echo "✅ 防火墙配置完成"
else
    echo "⚠️  防火墙未启用"
fi

# 9. 配置 SELinux
echo ""
echo "配置 SELinux..."
if [ -f /etc/selinux/config ]; then
    setenforce 0 2>/dev/null || true
    sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
    echo "✅ SELinux 已禁用"
fi

# 10. 创建 Nginx 配置
echo ""
echo "创建 Nginx 配置..."
cat > /etc/nginx/conf.d/oy-promotion.conf <<'NGINXEOF'
server {
    listen 80;
    server_name _;
    
    root /var/www/oy-promotion;
    index index.html;
    
    location / {
        try_files $uri $uri/ /index.html;
    }
    
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
NGINXEOF

# 11. 测试 Nginx 配置
echo ""
echo "测试 Nginx 配置..."
nginx -t

# 12. 启动 Nginx
echo ""
echo "启动 Nginx..."
systemctl start nginx
systemctl enable nginx

# 13. 检查状态
echo ""
if systemctl is-active --quiet nginx; then
    echo "✅ Nginx 运行正常"
else
    echo "❌ Nginx 启动失败"
    exit 1
fi

echo ""
echo "=================================="
echo "✅ 配置完成！"
echo "=================================="
echo ""
echo "服务器 IP: $(hostname -I | awk '{print $1}')"
echo "访问: http://$(hostname -I | awk '{print $1}')"
echo ""
echo "下一步: 运行 .\deploy-simple.ps1 部署项目"
echo ""
